package com.cmy.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.cmy.pojo.Role;
import com.cmy.pojo.User;
import com.cmy.service.role.RoleService;
import com.cmy.service.role.RoleServiceImp1;
import com.cmy.service.user.UserService;
import com.cmy.service.user.UserServiceImp1;
import com.cmy.util.Constant;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

//实现servlet复用,将方法提出来(跟前端隐藏域结合)
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method.equals("savepwd")&&method!=null){
            this.updatePwd(req,resp);
        }else if(method.equals("pwdmodify")&&method!=null){
            this.pwdModify(req,resp);
        }else if (method.equals("query")&&method!=null){
            this.query(req,resp);
        }else if (method.equals("add")&&method!=null){
            this.add(req,resp);
        }else if(method.equals("getrolelist")&&method!=null){
            this.getRoleList(req,resp);
        }else if(method.equals("ucexist")&&method!=null){
            this.userCodeExist(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
        //从session中获取id
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        String newpassword = req.getParameter("newpassword");

        boolean flag=false;

        if (o!=null&& !StringUtils.isNullOrEmpty(newpassword)){
            UserServiceImp1 userService = new UserServiceImp1();
            flag = userService.updatePwd(((User) o).getId(), newpassword);
            if (flag){
                req.setAttribute("message","修改密码成功,请退出并使用新密码登录");
                //密码修改成功,移除当前session
                req.getSession().removeAttribute(Constant.USER_SESSION);
            }else {
                req.setAttribute("message","修改密码失败");
            }

        }else{
            req.setAttribute("message","新密码存在问题");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //验证旧密码,session中存了用户的密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从session中获取id
        Object o = req.getSession().getAttribute(Constant.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        HashMap<String, String> resultMap = new HashMap<String, String>();

        if (o==null){//session失效了,过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) o).getUserPassword();//原密码
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //利用阿里巴巴的json转换工具将map转json(自己拼接字符也可以)
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //用户管理
    public void query(HttpServletRequest req, HttpServletResponse resp){

        //从前端获取数据
        String queryname = req.getParameter("queryname");
        String queryRoleNo = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;//默认为0
        //前端数据准备
        //页面,页码的初始化
        int pageSize = 5;
        int currentPageNo = 1;

        //解析前端数据
        if (queryname == null){
            queryname="";
        }
        if (queryRoleNo!=null&&!queryRoleNo.equals("")){
            queryUserRole = Integer.parseInt(queryRoleNo);//给角色查询赋值 0,1,2,3
        }
        if (pageIndex!=null){
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数
        UserServiceImp1 userService = new UserServiceImp1();
        int totalCount = userService.getUserCount(queryname,queryUserRole);
        int totalPages = 0;

        //根据totalCount和pageSize计算出总的页数
        if (totalCount%pageSize==0){
            totalPages = totalCount/pageSize;
        }else {
            totalPages = (int)(totalCount/pageSize)+1;
        }
        //分页 在已知用户总数,pageSize,currentPageNo的情况下
        if (currentPageNo<1){
            currentPageNo=1;//首页之前,无页面
        }else if (currentPageNo>totalPages){
            currentPageNo=totalPages;//尾页之后,无尾页
        }

        //获取用户列表
        List<User> userList = userService.getUserList(queryname, queryUserRole, currentPageNo, pageSize);
        //获取角色列表
        RoleServiceImp1 roleService = new RoleServiceImp1();
        List<Role> roleList = roleService.getRoleList();

        //将后端数据返回前端
        req.setAttribute("queryUserName",queryname);
        req.setAttribute("queryUserRole",queryUserRole);
        req.setAttribute("roleList",roleList);
        req.setAttribute("userList",userList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPages);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //添加用户
    public void add(HttpServletRequest req, HttpServletResponse resp){
        //创建用户
        User newUser = new User();
        newUser.setUserCode(req.getParameter("userCode"));
        newUser.setUserName(req.getParameter("userName"));
        newUser.setUserPassword(req.getParameter("userPassword"));
        newUser.setGender(Integer.parseInt(req.getParameter("gender")));
        try {
            newUser.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        newUser.setPhone(req.getParameter("phone"));
        newUser.setAddress(req.getParameter("address"));
        newUser.setUserRole(Integer.parseInt(req.getParameter("userRole")));
        //添加时间和操作的人
        newUser.setCreationDate(new Date());
        newUser.setCreatedBy(((User)req.getSession().getAttribute(Constant.USER_SESSION)).getId());

        UserServiceImp1 userService = new UserServiceImp1();
        if (userService.addUser(newUser)){
            try {
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            try {
                req.getRequestDispatcher("useradd.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void getRoleList(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException{
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImp1();
        roleList = roleService.getRoleList();
        //把roleList转换成json对象输出
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(roleList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }


    private void userCodeExist(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //判断用户账号是否可用
        String userCode = request.getParameter("userCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if(StringUtils.isNullOrEmpty(userCode)){
            //userCode == null || userCode.equals("")
            resultMap.put("userCode", "exist");
        }else{
            UserService userService = new UserServiceImp1();
            try {
                if (userService.userCodeExist(userCode)){
                    resultMap.put("userCode", "exist");
                }else {
                    resultMap.put("userCode", "noexist");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        //把resultMap转为json字符串以json的形式输出
        //配置上下文的输出类型
        response.setContentType("application/json");
        //从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = response.getWriter();
        //把resultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush();//刷新
        outPrintWriter.close();//关闭流
    }
}

    